#include "login.h"

//获得盐值
static void get_salt(char *salt);
//查找表
//返回值0表示注册成功，-1表示注册失败
int judge_register(int user_id, char *name, char *password, MYSQL *mysql_con){

    char buf[1024] = { 0 };
    sprintf(buf, "select * from user where user_id = %d", user_id);
    //mysql_query该函数成功返回0，不成功返回非0
    if (mysql_query(mysql_con, buf)) {
        printf("%s\n", mysql_error(mysql_con));
        return -1;
    }

    char salt[20] = { 0 };
    get_salt(salt);
    MYSQL_RES *result;
    MYSQL_ROW row;
    result = mysql_store_result(mysql_con);
    if(!result || (mysql_num_rows(result) == 0)){
        mysql_free_result(result);
        //该用户ID不存在可以使用
        char buf[1024] = { 0 };
        sprintf(buf,"insert into user values(%d, '%s', '%s', 1, '%s')", user_id, name, crypt(password, salt), salt);
        //在数据库中加入用户
        if (mysql_query(mysql_con, buf)) {
            printf("%s\n", mysql_error(mysql_con));
            return -1;
        }

        //为该用户创建根目录
        bzero(buf, sizeof(buf));
        sprintf(buf, "insert into file (status, file_name, user_name, father_id, path, file_type, md5, sha1)"
                "values(1, '/', '%s', -1, '/', 'd', null, null)", name);
        if (mysql_query(mysql_con, buf)) {
            printf("%s\n", mysql_error(mysql_con));
            return -1;
        }
        return 0;
    }

    row = mysql_fetch_row(result);
    mysql_free_result(result);

    if(strcmp("-1", row[3]) == 0){
        //该用户ID存在但是已经被别人注销了，也可以使用
        bzero(buf, sizeof(buf));
        sprintf(buf,"insert into user values(%d, '%s', '%s', 1, '%s')", user_id, name, crypt(password, salt), salt);
        if (mysql_query(mysql_con, buf)) {
            printf("%s\n", mysql_error(mysql_con));
            return -1;
        }

        bzero(buf, sizeof(buf));
        sprintf(buf, "insert into file (status, file_name, user_name, father_id, path, file_type, md5, sha1)"
                "values(1, '/', '%s', -1, '/', 'd', null, null)", name);
        if (mysql_query(mysql_con, buf)) {
            printf("%s\n", mysql_error(mysql_con));
            return -1;
        }
        return 0;
    }
    //该ID存在正在被人使用
    return -1;

}
static void get_salt(char *salt){
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    size_t charset_size = sizeof(charset) - 1;

    srand(time(NULL));
    char buf[9] = { 0 };
    for(int i = 0; i < 8; i++){
        buf[i] = charset[rand()%charset_size];
    }
    sprintf(salt, "$6$%s$", buf);
}
